from flask import Flask, render_template, request, jsonify
from flask_cors import CORS
import pymysql
import random
import string
import time
import smtplib
from email.mime.text import MIMEText

app = Flask(__name__, template_folder='templates')
CORS(app)  # 启用 CORS
app.config['SECRET_KEY'] = 'your_secret_key'  # 用于 JWT 签名的密钥，需要保密

# 数据库配置
db_config = {
    'host': 'localhost',
    'user': 'root',
    'password': 'mimashi0',
    'database': 'huiwen'
}

# 邮箱配置（需要替换为实际可用的邮箱配置）
EMAIL_CONFIG = {
    'sender': '1476164672@qq.com',  # 发件人邮箱
    'password': 'mapfcxblifgkjbej',  # 邮箱密码/授权码
    'smtp_server': 'smtp.qq.com',    # SMTP服务器地址
    'smtp_port': 465                 # SMTP端口
}

# 验证码存储字典（实际生产环境应使用数据库或Redis）
verification_codes = {}

# 首页路由
@app.route('/')
def init():
    return render_template('init.html')

# 注册页面路由
@app.route('/register')
def register_page():
    return render_template('register.html')

# 登录页面路由
@app.route('/login')
def login_page():
    return render_template('login.html')

# 首页
@app.route('/index')
def index():
    return render_template('index.html')

# 修改注册API（添加验证码验证）
@app.route('/api/register', methods=['POST', 'OPTIONS'])
def register():
    if request.method == 'OPTIONS':
        return jsonify({'message': 'CORS preflight request successful'}), 200

    data = request.get_json()
    username = data.get('username')
    email = data.get('email')
    password = data.get('password')
    verificationCode = data.get('verificationCode')  # 获取验证码

    if not username or not email or not password or not verificationCode:
        return jsonify({'message': '缺少必填字段'}), 400

    # 验证验证码
    if email in verification_codes:
        code_info = verification_codes[email]
        # 检查验证码是否过期
        if time.time() > code_info['expire']:
            return jsonify({'message': '验证码已过期'}), 400
        # 检查验证码是否正确
        if verificationCode != code_info['code']:
            return jsonify({'message': '验证码错误'}), 400
        # 验证通过后删除验证码
        del verification_codes[email]
    else:
        return jsonify({'message': '请先获取验证码'}), 400

    try:
        connection = pymysql.connect(**db_config)
        with connection.cursor() as cursor:
            sql = "INSERT INTO users (username, email, password) VALUES (%s, %s, %s)"
            cursor.execute(sql, (username, email, password))
        connection.commit()
        return jsonify({'message': '注册成功'})
    except pymysql.err.IntegrityError as e:
        if 'Duplicate entry' in str(e):
            if 'username' in str(e):
                return jsonify({'message': '用户名已存在'}), 400
            elif 'email' in str(e):
                return jsonify({'message': '邮箱已存在'}), 400
    except Exception as e:
        print(f"错误: {e}")
        return jsonify({'message': '服务器错误'}), 500
    finally:
        if 'connection' in locals():
            connection.close()

# 登录 API - 修改点：添加重定向路径
@app.route('/api/login', methods=['POST', 'OPTIONS'])
def login():
    if request.method == 'OPTIONS':
        return jsonify({'message': 'CORS preflight request successful'}), 200

    data = request.get_json()
    username = data.get('username')
    password = data.get('password')

    if not username or not password:
        return jsonify({'message': '缺少必填字段'}), 400

    try:
        connection = pymysql.connect(**db_config)
        with connection.cursor() as cursor:
            sql = "SELECT password FROM users WHERE username = %s"
            cursor.execute(sql, (username,))
            user = cursor.fetchone()

        if not user:
            return jsonify({'message': '用户名不存在'}), 400

        if user[0] == password:
            # 登录成功时返回重定向路径
            return jsonify({
                'message': '登录成功',
                'redirect': '/index'  # 添加重定向路径
            })
        else:
            return jsonify({'message': '密码错误'}), 400
    except Exception as e:
        print(f"错误: {e}")  # 打印错误信息到终端
        return jsonify({'message': '服务器错误'}), 500
    finally:
        if 'connection' in locals():
            connection.close()


# 发送验证码函数
def send_verification_email(email, code):
    server = None
    try:
        # 邮件内容
        subject = "汇问注册验证码"
        body = f"您的注册验证码是：<b>{code}</b><br>该验证码5分钟内有效，请勿泄露给他人。"

        # 创建邮件对象
        msg = MIMEText(body, 'html')
        msg['Subject'] = subject
        msg['From'] = EMAIL_CONFIG['sender']
        msg['To'] = email

        # 发送邮件 - 使用SMTP_SSL
        server = smtplib.SMTP_SSL(EMAIL_CONFIG['smtp_server'], EMAIL_CONFIG['smtp_port'])
        server.login(EMAIL_CONFIG['sender'], EMAIL_CONFIG['password'])
        server.sendmail(EMAIL_CONFIG['sender'], [email], msg.as_string())
        print(f"邮件已成功发送至: {email}")
        return True
    except smtplib.SMTPException as e:
        print(f"SMTP发送邮件失败: {e}")
        return False
    except Exception as e:
        print(f"发送邮件出现意外错误: {e}")
        return False
    finally:
        if server:
            try:
                server.quit()  # 更优雅地关闭连接
            except:
                pass  # 忽略退出时的错误


# 修改验证码发送API
@app.route('/api/send_verification_code', methods=['POST', 'OPTIONS'])
def send_verification_code():
    if request.method == 'OPTIONS':
        return jsonify({'message': 'CORS preflight request successful'}), 200

    data = request.get_json()
    email = data.get('email')

    if not email:
        return jsonify({'message': '邮箱不能为空'}), 400

    try:
        # 检查邮箱是否已注册
        connection = pymysql.connect(**db_config)
        with connection.cursor() as cursor:
            sql = "SELECT email FROM users WHERE email = %s"
            cursor.execute(sql, (email,))
            if cursor.fetchone():
                return jsonify({'message': '该邮箱已注册'}), 400
    except Exception as e:
        print(f"数据库错误: {e}")
        return jsonify({'message': '服务器错误'}), 500
    finally:
        if 'connection' in locals():
            connection.close()

    # 生成6位随机验证码
    code = ''.join(random.choices(string.digits, k=6))
    timestamp = time.time()

    # 保存验证码（有效期5分钟）
    verification_codes[email] = {
        'code': code,
        'expire': timestamp + 300  # 5分钟有效期
    }

    # 发送邮件（不再检查发送结果）
    try:
        send_verification_email(email, code)
        print(f"验证码: {code}")  # 开发环境记录
        return jsonify({'message': '验证码已发送'})
    except Exception as e:
        print(f"发送过程中出现异常: {e}")
        print(f"验证码: {code}")
        return jsonify({'message': '验证码已发送'})

# 在现有代码中添加登出路由
@app.route('/api/logout', methods=['POST', 'OPTIONS'])
def logout():
    if request.method == 'OPTIONS':
        return jsonify({'message': 'CORS preflight request successful'}), 200

    # 如果是基于会话的认证，可以清除会话
    # session.clear()  # 取消注释如果使用Flask session

    return jsonify({
        'message': '登出成功',
        'redirect': '/login'  # 重定向到登录页
    })

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=8000, debug=True)